<script setup lang="ts">
import ImageAnnotator from '@/components/imageAnnotator/index.vue'
import type { ColorMarkAreaConfig, ImageAnnotatorButtons } from '@/types'
import DesignerView from '@/views/designer/index.vue'
import { ref, useTemplateRef } from 'vue'
import dataBaseDesignerChain from '@/chains/DataBaseDesignerChain.ts'
import FcDesignerChain from '@/chains/FcDesignerChain.ts'
import MarkdownRenderer from '@/components/MarkdownRenderer/index.vue'
import { ElLoading, ElMessage } from 'element-plus'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'

const imageAnnotatorRef = useTemplateRef('ImageAnnotatorRef')

const designerDrawer = ref(false)
const markdownDrawer = ref(false)
const areaColorRemarkDialogVisible = ref(false)
const areaColorRemarkConfig = ref<ColorMarkAreaConfig[]>([])
const designerRule = ref<string | null>(null);

const dataBaseDesignerMd = ref("")


function showLoading(): LoadingInstance {
  return ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}
const buttons: ImageAnnotatorButtons[] = [
  {
    type: 'default',
    label: '生成',
    icon: 'Plus',
    action: analyseCanvas,
  },
  {
    type: 'default',
    label: 'ER',
    icon: 'Plus',
    action: async () => {
      markdownDrawer.value = true

    },
  },
  {
    type: 'default',
    label: '设计器',
    icon: 'Plus',
    action: () => {
      designerDrawer.value = true
    },
  },
]

async function analyseCanvas() {
  console.log(imageAnnotatorRef.value?.getUsedColors())
  if (areaColorRemarkConfig.value.length > 0) {
    areaColorRemarkConfig.value = []
  }
  const colors = imageAnnotatorRef.value?.getUsedColors() ?? []
  areaColorRemarkConfig.value.push(
    ...colors.map(
      (color) =>
        ({
          color,
          tag: [],
        }) as ColorMarkAreaConfig,
    ),
  )
  areaColorRemarkDialogVisible.value = true

  // console.log(res.content)
}

/**
 *
 */
async function generateDataBaseInfo() {
  areaColorRemarkDialogVisible.value = false

  const loadingInstance = showLoading()
  const base64 = imageAnnotatorRef.value?.generateAsBase64()
  console.log(base64)
  const res = await dataBaseDesignerChain.invoke({
    base64: base64,
    description: `区域颜色配置：${JSON.stringify(areaColorRemarkConfig.value)}`,
  })
  loadingInstance.close();
  // 显示数据表关系建立信息
  console.log(res.content)
  dataBaseDesignerMd.value = typeof res.content === 'string'
    ? res.content
    : JSON.stringify(res.content || []);
  markdownDrawer.value = true
  ElMessage.primary('数据模型分析建立完成')
}

async function generateFcDesigner() {
  const loadingInstance = showLoading()
  ElMessage.primary("开始构建表单")
  const resD = await FcDesignerChain.invoke({
    description: dataBaseDesignerMd.value,
  })
  console.log(resD.content)
  designerRule.value = typeof resD.content === 'string'
    ? resD.content.replace(/```json\s*([\s\S]*?)```/g, '$1').trim()
    : JSON.stringify(resD.content || []);


  markdownDrawer.value = false
  designerDrawer.value = true
  loadingInstance.close();
  ElMessage.success("表单构建完成")
}
</script>

<template>
  <div class="canvas-view">
    <ImageAnnotator ref="ImageAnnotatorRef" :buttons="buttons"></ImageAnnotator>
  </div>

  <el-dialog v-model="areaColorRemarkDialogVisible" title="区域颜色配置" width="400">
    <el-form>
      <el-form-item
        label="Activity name"
        v-for="(item, index) in areaColorRemarkConfig"
        :key="index"
      >
        <template #label>
          <div
            :style="{
              width: '25px',
              height: '25px',
              border: `1px solid ${item.color}`,
              borderRadius: '4px',
              backgroundColor: item.color,
            }"
          ></div>
        </template>
        <template #default>
          <el-input-tag
            v-model="item.tag"
            placeholder="Please input"
            aria-label="Please click the Enter key after input"
          />
        </template>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="areaColorRemarkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateDataBaseInfo"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-drawer
    class="markdown-drawer"
    body-class="markdown-drawer-body"
    v-model="markdownDrawer"
    title="ER图设计结果"
    :with-header="false"
    size="80%"
  >
    <MarkdownRenderer :markdown="dataBaseDesignerMd" />
    <template #footer>
      <div style="flex: auto">
        <el-button @click="markdownDrawer = false">关闭</el-button>
        <el-button type="primary" @click="generateFcDesigner">下一步</el-button>
      </div>
    </template>
  </el-drawer>

  <el-drawer
    class="designer-drawer"
    body-class="designer-drawer-body"
    v-model="designerDrawer"
    title="设计器"
    :with-header="false"
    size="90%"
  >
    <DesignerView :rule="designerRule"/>
  </el-drawer>
</template>

<style scoped>
.canvas-view {
  width: 100%;
  height: 100%;
}

.area-color-remark-item {
  display: flex;
}
</style>
